package com.jiang.jetpackdemo.fragment

import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager

import com.jiang.jetpackdemo.R
import com.jiang.jetpackdemo.activity.NewsContentActivity
import com.jiang.jetpackdemo.adapter.MyOnClickListener
import com.jiang.jetpackdemo.adapter.News2Adapter
import kotlinx.android.synthetic.main.music_recommend_fragment.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

class NewsRecommendFragment : Fragment() {
    companion object {
        fun newInstance() = NewsRecommendFragment()
        const val INTENT_KEY = "NewsRecommendFragment"
    }

    lateinit var adapter: News2Adapter
    private lateinit var viewModel: NewsRecommendViewModel


    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.music_recommend_fragment, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        initViewModel()
        initView()
        viewModel.getData()
    }

    private fun initView() {
        adapter = News2Adapter(context!!, viewModel.getNewsList(), R.layout.item_rv_news)
        rv_news.adapter = adapter
        rv_news.layoutManager = LinearLayoutManager(context!!, LinearLayoutManager.VERTICAL, false)
        try {
            srl_news.setOnRefreshListener { GlobalScope.launch(Dispatchers.Main) { viewModel.getDataFromNet() } }
        } catch (e: Exception) {
            Log.e("setOnRefreshListener", e.message, e)
        }
        adapter.setMyOnClickListener(object : MyOnClickListener {
            override fun onClick(pos: Int) {
                val intent = Intent(context, NewsContentActivity::class.java)
                intent.putExtra(INTENT_KEY, adapter.list[pos].contentUrl)
                startActivity(intent)
            }
        })

    }

    private fun initViewModel() {
        viewModel = ViewModelProvider(this).get(NewsRecommendViewModel::class.java)
        viewModel.initTool(context!!)
        viewModel.getSizeOfNewsList()
            .observe(viewLifecycleOwner, Observer {
                adapter.notifyDataSetChanged()
                if (srl_news.isRefreshing) srl_news.isRefreshing = false
            })
    }

    override fun onDestroy() {
        super.onDestroy()
        viewModel.closeDb()
    }
}
